package com.yuexun.dhdoctor.module.commun.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.baselistener.OnDataBackListener;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.config.DbConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.Contract.adapter.CreateGroupAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.ChildDepartmentsBean;
import com.yuexun.dhdoctor.module.Contract.bean.DepartOrPeopleData;
import com.yuexun.dhdoctor.module.Contract.bean.GroupDataBean;
import com.yuexun.dhdoctor.module.Contract.bean.GroupGroupData;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.Contract.bean.UsersBean;
import com.yuexun.dhdoctor.module.Contract.model.impl.DepartmentModel;
import com.yuexun.dhdoctor.module.Contract.presenter.impl.DepartmentPresenter;
import com.yuexun.dhdoctor.module.Contract.ui.view.IDepartmentView;
import com.yuexun.dhdoctor.module.commun.adapter.DepartAndGroup_Depart_Adapter;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;


import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/3/27 0027.
 */

public class Act_DepartAndGroup_Depart extends BaseKJActivity implements IDepartmentView {

    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.right)
    CheckBox cbAll;

    @Bind(R.id.search_view)
    FrameLayout searchView;
    @Bind(R.id.etSearch2)
    EditText etSearch2;
    @Bind(R.id.btnSearchClear)
    ImageButton btnSearchClear;
    @Bind(R.id.searchLayout)
    LinearLayout searchLayout;

    @Bind(R.id.dept_list)
    FixedSwipeListView deptList;
    @Bind(R.id.people_list)
    FixedSwipeListView peopleList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.grid)
    GridView grid;
    @Bind(R.id.addmember_sure_btn)
    TextView addmemberSureBtn;

    private Handler handler;

    private DepartmentPresenter presenter;

    ArrayList<People> usersBeans_origin = new ArrayList<>();
    ArrayList<People> peoples = new ArrayList<>();

    private KJDB kjdb;
    private List<GroupDataBean> datas;
    private ArrayList departmentBeans;

    private OnDataBackListener listener;
    //0：不能选择自己  1：能选择
    private int isSelectMe;

    @Override
    public void setRootView() {
        super.setRootView();
        setContentView(R.layout.act_choice_department);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        initView();
        initHandle();
        presenter = new DepartmentPresenter(new DepartmentModel(), this);
        departmentBeans = (ArrayList<People>) getIntent().getExtras().getSerializable("departmentBeans");
        String departmentId = getIntent().getExtras().getString("departmentId");
        isSelectMe = getIntent().getExtras().getInt("isSelectMe", 0);

        setGridView();

        kjdb = KJDB.create(this, DbConfig.DBNAME, DbConfig.ISDEBUG, DbConfig.DBVERSION, new KJDB.DbUpdateListener() {
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                if(newVersion>oldVersion)
                {
                    Cursor cursor = db.rawQuery(
                            "SELECT name FROM sqlite_master WHERE type ='table'", null);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            // 添加异常捕获.忽略删除所有表时出现的异常:
                            // table sqlite_sequence may not be dropped
                            try {
                                db.execSQL("DROP TABLE " + cursor.getString(0));
                            } catch (SQLException e) {
                                KJLoger.debug(getClass().getName() + e.getMessage());
                            }
                        }
                    }
                    if (cursor != null) {
                        cursor.close();
                        cursor = null;
                    }
                }
            }
        });

        datas = (ArrayList<GroupDataBean>) kjdb.findAllByWhere(GroupDataBean.class, "department_id = '" + departmentId + "'");
        if (datas != null && datas.size() > 0) {
            refresh(datas);
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
            params.put("parentDepartmentId", departmentId);
            presenter.getGroupDatas(params);
        }
    }

    @SuppressLint("HandlerLeak")
    void initHandle() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 10003:
                        setGridView();
                        if (listener != null) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("departmentBeans", departmentBeans);
                            listener.showData(bundle);
                        }
                        break;
                }
            }
        };
    }

    private void initView() {
        cbAll.setVisibility(View.GONE);
        searchView.setVisibility(View.GONE);

        deptList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ChildDepartmentsBean childDepartmentsBean = (ChildDepartmentsBean) parent.getItemAtPosition(position);
                datas = (ArrayList<GroupDataBean>) kjdb.findAllByWhere(GroupDataBean.class, "department_id = " + childDepartmentsBean.getDepartment_id());
                if (datas != null && datas.size() > 0) {
                    refresh(datas);
                } else {
                    Map<String, String> params = new HashMap<>();
                    params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
                    params.put("parentDepartmentId", childDepartmentsBean.getDepartment_id() + "");
                    presenter.getGroupDatas(params);
                }
            }
        });
    }

    @Override
    @OnClick({R.id.dept_back, R.id.btnSearchClear, R.id.addmember_sure_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dept_back:
                onBackPressed();
                break;
            case R.id.btnSearchClear:
                etSearch2.setText("");
                break;
            case R.id.addmember_sure_btn:
                if (departmentBeans.size() == 0) {
                    Toast.makeText(this, "请选择接收对象", Toast.LENGTH_SHORT).show();
                } else {
                    Bundle bundle = new Bundle();
                    Intent intent = new Intent();
                    bundle.putSerializable("departmentBeans", departmentBeans);
                    intent.putExtras(bundle);
                    setResult(10003, intent);
                    finish();
                }
                break;
        }
    }

    @Override
    public void showGroupDatas(BaseEntity<GroupDataBean> groupBean) {
        if ("200".equals(groupBean.getStatus())) {
            datas = groupBean.getDatas();
            refresh(groupBean.getDatas());
            kjdb.save(groupBean.getDatas());
        } else {
            ViewInject.toast("获取数据失败");
        }
    }

    private void refresh(List<GroupDataBean> datas) {
        if (datas.size() > 0) {
//            List<ChildDepartmentsBean> listPerson = JSON.parseArray(datas.get(0).getChildDepartments(), ChildDepartmentsBean.class);
//            List<UsersBean> usersBeen = JSON.parseArray(datas.get(0).getUsers(), UsersBean.class);

            List<GroupDataBean> listPerson = datas.get(0).getChildDepartments();
            List<UsersBean> usersBeen = datas.get(0).getUsers();

            DepartAndGroup_Depart_Adapter adapter_dept = new DepartAndGroup_Depart_Adapter(deptList, listPerson, R.layout.item_department, departmentBeans, handler, isSelectMe);
            deptList.setAdapter(adapter_dept);

            peoples.clear();
            for (int i = 0; i < usersBeen.size(); i++) {
                People people = new People();
                if (usersBeen.get(i).getAccount_id() != null) {
                    //TODO 需要使用account_id
                    people.setUserId(usersBeen.get(i).getAccount_id());
                } else {
                    people.setUserId(usersBeen.get(i).getUser_id());
                }
                people.setUserName(usersBeen.get(i).getUser_name());
                people.setJobNum(usersBeen.get(i).getJobNum());
                people.setPinyin(usersBeen.get(i).getPinyin());
                peoples.add(people);
            }
            AddMemberAdapter addMemberAdapter = new AddMemberAdapter(aty, peoples, usersBeans_origin, handler, 0, peopleList, true);
            peopleList.setAdapter(addMemberAdapter);
            emptyLayout.dismiss();
            titleTv.setText(datas.get(0).getDepartment_name());
        }
    }

    private void setGridView() {
        int size = departmentBeans.size();

        List<DepartOrPeopleData> datas = new ArrayList<>();

        for (int i = 0; i < departmentBeans.size(); i++) {
            if (departmentBeans.get(i) instanceof ChildDepartmentsBean) {
                DepartOrPeopleData data = new DepartOrPeopleData();
                data.setDataId(((ChildDepartmentsBean) departmentBeans.get(i)).getDepartment_id() + "");
                data.setDataName(((ChildDepartmentsBean) departmentBeans.get(i)).getDepartment_name());
                datas.add(data);
            } else if (departmentBeans.get(i) instanceof GroupGroupData) {
                DepartOrPeopleData data = new DepartOrPeopleData();
                data.setDataId(((GroupGroupData) departmentBeans.get(i)).getGroupId() + "");
                data.setDataName(((GroupGroupData) departmentBeans.get(i)).getTitle());
                datas.add(data);
            }
        }

        if (size == 0) {
            addmemberSureBtn.setBackgroundResource(R.color.doc_advice_02);
            addmemberSureBtn.setEnabled(false);
        } else {
            addmemberSureBtn.setBackgroundResource(R.color.doc_advice_01);
            addmemberSureBtn.setEnabled(true);
        }

        addmemberSureBtn.setText("确认");

        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        grid.setLayoutParams(params); // 重点
        grid.setColumnWidth(itemWidth); // 重点
        grid.setHorizontalSpacing(5); // 间距
        grid.setStretchMode(GridView.NO_STRETCH);
        grid.setNumColumns(size); // 重点

        CreateGroupAdapter adapter = new CreateGroupAdapter(grid, datas, R.layout.item_send_addmember);
        grid.setAdapter(adapter);
    }

    @Override
    public void onBackPressed() {
        if (datas != null && datas.size() > 0 && datas.get(0).getParent_department_id() != 1) {
            datas = (ArrayList<GroupDataBean>) kjdb.findAllByWhere(GroupDataBean.class,
                    "department_id = " + datas.get(0).getParent_department_id());
            refresh(datas);
        } else {
            Bundle bundle = new Bundle();
            Intent intent = new Intent();
            bundle.putSerializable("departmentBeans", departmentBeans);
            intent.putExtras(bundle);
            setResult(0x001, intent);
            finish();
        }
    }
}
